package fr.sportcom.sportcom.controller;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import fr.sportcom.sportcom.R;
import fr.sportcom.sportcom.SportComApplication;
import fr.sportcom.sportcom.adapter.SportsListAdapter;
import fr.sportcom.sportcom.model.AdsManager;
import fr.sportcom.sportcom.model.CSport;
import fr.sportcom.sportcom.model.CustomHttpClient;
import fr.sportcom.sportcom.model.User;
import fr.sportcom.sportcom.model.UserPanel;

public class SportListActivity extends Activity implements OnItemClickListener {

	private ArrayList<CSport> lSport = new ArrayList<CSport>();
	private ListView SportView;
	private View mloadingStatusView;
	private User mLoggedUser;
	private boolean drawPref = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_sport_list);

		setContentView(R.layout.sponso_layout);
		View appContent = LayoutInflater.from(this).inflate(
				R.layout.activity_sport_list, 
				(ViewGroup) this.findViewById(R.id.app_content), 
				false);
		((LinearLayout)this.findViewById(R.id.app_content)).addView(appContent);
		
		SportComApplication app = (SportComApplication) (this.getApplication());
		app.initAds();
		
		mLoggedUser = app.getLoggedUser();

		String defaultMail = "";
		
		if(mLoggedUser == null) {
			// On pr�pare l'activit� avec le param selectionn�.
			Intent intentEvent = new Intent(SportListActivity.this, LoginActivity.class);
			intentEvent.putExtra(LoginActivity.EXTRA_EMAIL, defaultMail);
			startActivityForResult(intentEvent, 1);
		}

		SportView = (ListView) findViewById(R.id.listSport);
		mloadingStatusView = findViewById(R.id.loading_status);

		showProgress(true);
		RefreshListTask mRefresh = new RefreshListTask();
		mRefresh.link(this);
		mRefresh.execute();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		AdsManager.displayAds(this);

		if(drawPref) {
			mLoggedUser = ((SportComApplication) (this.getApplication())).getLoggedUser();
			
			if(mLoggedUser == null) {
				// On pr�pare l'activit� avec le param selectionn�.
				Intent intentEvent = new Intent(SportListActivity.this, LoginActivity.class);
				intentEvent.putExtra(LoginActivity.EXTRA_EMAIL, "");
				startActivityForResult(intentEvent, 1);
			}
			drawPref = false;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_sport_list, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.panel_setting) {
			drawPref = true;
		}
		UserPanel.panelOption(item, this);
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		// On pr�pare l'activit� avec le param selectionn�.
		Intent intentEvent = EventListActivity.prepareIntent(SportListActivity.this, EventListActivity.SPORT, lSport.get(pos));
		startActivity(intentEvent);
	}

	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mloadingStatusView.setVisibility(View.VISIBLE);
			mloadingStatusView.animate().setDuration(shortAnimTime)
			.alpha(show ? 1 : 0)
			.setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					mloadingStatusView.setVisibility(show ? View.VISIBLE
							: View.GONE);
				}
			});

			SportView.setVisibility(View.VISIBLE);
			SportView.animate().setDuration(shortAnimTime)
			.alpha(show ? 0 : 1)
			.setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					SportView.setVisibility(show ? View.GONE
							: View.VISIBLE);
				}
			});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mloadingStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			SportView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// On v�rifie tout d'abord � quel intent on fait r�f�rence ici � l'aide de notre identifiant
		if (requestCode == 1) {
			// On v�rifie aussi que l'op�ration s'est bien d�roul�e
			if (resultCode != RESULT_OK) {
				this.finish();
			}
		}
	}


	private class RefreshListTask extends AsyncTask<Void, Void, Boolean> {

		private WeakReference<SportListActivity> mActivity = null;

		@Override
		protected Boolean doInBackground(Void... params) {

			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			try {
				//Thread.sleep(5000);
				jObj = request.postData("loadSportList");

				if(jObj.getInt("back") != 0) {
					return false;
				}

				lSport.clear();
				JSONArray list = jObj.getJSONArray("list");
				for(int i=0; i<list.length(); i++) {
					CSport spr = new CSport(
							list.getJSONObject(i).getInt("spr_id"), 
							list.getJSONObject(i).getString("spr_libelle")
							);
					lSport.add(spr);
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(mActivity.get(), "Une erreur est survenue.", Toast.LENGTH_LONG).show();
				return;
			}

			SportsListAdapter adapt = new SportsListAdapter(mActivity.get(), lSport);
			SportView.setAdapter(adapt);

			SportView.setOnItemClickListener(mActivity.get());

			showProgress(false);
		}

		public void link (SportListActivity pActivity) {
			mActivity = new WeakReference<SportListActivity>(pActivity);
		}
	}
}
